﻿using System.Collections.Generic;
using System.Configuration;
using System.Net.NetworkInformation;
using System.Text;
using RestSharp;

namespace Provausio.Server.Nzb.Poller.Logic
{
    public class NotifyServiceDownOperation
    {
        private const string ApplicationIdentifier = "Service Poller";
        private const string EventName = "Service(s) Down";
        private readonly string _notificationServiceUri;
        private readonly string _notificationServiceApikey;

        public NotifyServiceDownOperation()
        {
            _notificationServiceUri = ConfigurationManager.AppSettings["NotificationServiceUri"];
            _notificationServiceApikey = ConfigurationManager.AppSettings["NotificationServiceApiKey"];
        }

        public void Notify(IEnumerable<string> services)
        {
            var client = new RestClient(_notificationServiceUri);
            var request = new RestRequest("publicapi/notify", Method.GET);

            request.AddParameter("apikey", _notificationServiceApikey);
            request.AddParameter("application", ApplicationIdentifier);
            request.AddParameter("event", EventName);
            request.AddParameter("description", BuildMessage(services));

            client.Execute(request);
        }

        private static string BuildMessage(IEnumerable<string> services)
        {
            var sb = new StringBuilder();
            sb.Append("The following services did not response to pings: \r\n");
            foreach (var service in services)
            {
                sb.AppendFormat("- {0}\n", service);
            }

            return sb.ToString();
        }
    }
}
